const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
    username: { type: String },
    password: { type: String },
    roles: { type: String },
})

const shopListSchema = new mongoose.Schema([{
    url: { type: String },
    title: { type: String },
    desc: { type: String },
    price: { type: Number },
    count: { type: Number }
}])
const User = mongoose.model("User", userSchema, "users")
const ShopList = mongoose.model("ShopList", shopListSchema, "ShopLists")
module.exports = {
    init() {
        mongoose
            .connect("mongodb://127.0.0.1:27017/2302B", {
                useNewUrlParser: true,
            })
            .then(() => {
                console.log('成功链接到MongoDB数据库2302B')
            })
            .catch((e) => {
                console.log("连接失败")
                console.warn(e)
            })
    },
    async checkUser(username, password) {
        const user = await User.findOne({ username })
        return user && user.password == password
    },
    async register(username, password) {
        const user = await User.findOne({ username });
        if (user) {
            return user && `已存在用户名${user.username}`
        } else {
            const userRegister = await User.insertMany([{ username: username, password: password }])
            return userRegister && "注册成功"
        }
    },
    async searchShopListItem(obj) {
        const shopList = await ShopList.findOne({ id: obj.id })
        return shopList
    },
    async pushShopListItem(obj) {
        const shopList = await ShopList.findOne({ title: obj.title })
        if (shopList) {
            return shopList && "数据存在"
        } else {
            const shopList = await ShopList.insertMany([{
                url: obj.url,
                title: obj.title,
                desc: obj.desc,
                price: obj.price,
            }])
            return shopList && "添加成功"
        }
    }
}